import React, { useState, useEffect, useRef } from 'react';
import { useSize } from 'ahooks';
import { useThemeChange } from '@/hooks/useThemeChange';
import * as echarts from 'echarts';
// @ts-ignore
import { getCssVariableValue } from '@/utils/utils';
import './index.less';
import { Spin } from 'antd';

const buildSeries = (dataArr: any[], showChartObj: IDimensionChartsProps['showChartObj']) => {
  const series: any[] = [];
  const xAxis: string[] = [];
  const keys = Object.keys(showChartObj);
  for (let i = 0; i < dataArr.length; i++) {
    const item = dataArr[i];
    xAxis.push(item.dimension);
    keys.forEach((k, index) => {
      if (!series[index]) {
        const config: any = {
          name: showChartObj[k].name,
          type: showChartObj[k].type,
          color: showChartObj[k].color,
          data: [],
        };
        if (config.type === 'bar') {
          config.barMaxWidth = 8;
        }
        if (config.type === 'line') {
          config.symbol = 'circle';
          config.smooth = true;
        }

        if (showChartObj[k].stack) {
          config.stack = showChartObj[k].stack;
        }

        series[index] = config;
      }
      series[index].data.push(item[k]);
    });
  }

  return {
    series,
    xAxis,
  };
};

const getOptions = (series: any[], xAxis: string[]) => {
  return {
    grid: {
      left: '5%',
      right: '5%',
      top: 10,
      bottom: '10%',
      containLabel: true,
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: '#161A1D', // 设置背景颜色为黑色
      textStyle: {
        fontSize: 14,
        lineHeight: 14,
        color: '#A7A8A9',
      },
      borderWidth: 0,
      axisPointer: {
        type: 'line',
        lineStyle: { width: 1, color: '#4E5154', type: 'solid' },
      },
    },
    xAxis: {
      type: 'category',
      data: xAxis,
      axisPointer: {
        type: 'line',
        lineStyle: {
          type: 'solid',
          color: getCssVariableValue('--chart-x-line'),
        },
      },
      axisLine: {
        show: true,
        onZero: false,
        lineStyle: {
          type: 'solid',
          color: getCssVariableValue('--chart-x-line'),
        },
      },
      axisTick: {
        alignWithLabel: true,
        lineStyle: {
          color: getCssVariableValue('--chart-x-line'),
        },
      },
      axisLabel: {
        textStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
      },
    },
    yAxis: {
      type: 'value',
      axisTick: {
        alignWithLabel: true,
        length: 4,
        lineStyle: {
          color: getCssVariableValue('--chart-y-line'),
        },
      },
      axisLabel: {
        color: getCssVariableValue('--chart-font-color'),
        fontSize: 12,
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'solid',
          color: getCssVariableValue('--chart-y-line'),
        },
      },
    },
    legend: {
      bottom: 0, // 放置在底部
      left: 'center', // 水平居中
      textStyle: {
        color: getCssVariableValue('--chart-legend-color'),
      },
      itemWidth: 12, // 图标宽度
      itemHeight: 6, // 图标高度
    },
    series: series,
  };
};

const DimensionCharts: React.FC<IDimensionChartsProps> = (props) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstanceRef = useRef<echarts.ECharts | null>(null);
  const chartSize = useSize(chartRef);
  const { theme } = useThemeChange();

  useEffect(() => {
    if (chartRef.current) {
      chartInstanceRef.current = echarts.init(chartRef.current);
    }

    return () => {
      chartInstanceRef.current?.dispose();
    };
  }, []);

  useEffect(() => {
    if (!chartSize?.width) return;
    chartInstanceRef.current?.resize();
  }, [chartSize]);

  useEffect(() => {
    if (chartInstanceRef.current && props.currentChartsArr && props.currentChartsArr.length > 0) {
      const { series, xAxis } = buildSeries(props.currentChartsArr, props.showChartObj);
      setTimeout(() => {
        const options = getOptions(series, xAxis);
        chartInstanceRef.current && chartInstanceRef.current.setOption(options, true);
      }, 100);
    }
  }, [props.currentChartsArr, theme]);

  return (
    <div className="dimension-charts">
      <div className="charts-name">
        {props.name}
        {props.unit && <span className="unit">单位：{props.unit}</span>}
      </div>
      <Spin spinning={props.loading}>
        <div className="charts" ref={chartRef} />
      </Spin>
    </div>
  );
};

export type showChartObjType = {
  /**
   * 柱状图或图表名字
   */
  name: string;
  /**
   * 图表类型
   */
  type: 'line' | 'bar';
  /**
   * 线的颜色
   */
  color: string;
  /**
   * 柱状图合并
   */
  stack?: string;
};

interface IDimensionChartsProps {
  name: string;
  unit?: string;
  currentChartsArr: any[];
  showChartObj: Record<string, showChartObjType>;
  loading: boolean;
}

export default DimensionCharts;
